package com.qfedu.controller.controller;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qfedu.commons.bean.User;
import com.qfedu.commons.bean.result.QueryResult;
import com.qfedu.commons.bean.result.Result;
import com.qfedu.commons.bean.result.ResultEnum;
import com.qfedu.commons.serviceApi.UserService;
import com.qfedu.commons.utils.JWTUtil;
import com.qfedu.commons.utils.QiNiuUploadUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author No.1 王浩伟
 * @since 2022-07-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/selectById/{id}")//根据ID查用户
    public String selectById(@PathVariable("id") Long id){

        String jsonString = JSON.toJSONString(userService.selectById(id));

        return jsonString;

    }

    @RequestMapping("/login")//登录
    public String login(User user){

        Result rs = userService.login(user);

        return JSON.toJSONString(rs);

    }

    @RequestMapping("/register")//注册
    public String register(User user){

        Result result;

        if (userService.hasUsername(user.getUsername())){
            result = new Result(ResultEnum.ADD_ERROR);
            result.setMsg("用户名重复");
            return JSON.toJSONString(result);
        }

        if (userService.register(user)==1){
            result =new Result(ResultEnum.ADD_SUCCESS);
            return JSON.toJSONString(result);
        }

        return JSON.toJSONString(new Result(ResultEnum.ADD_ERROR));

    }

    @RequestMapping("/uploadImg")//上传头像
    public String uploadImg(MultipartFile file, HttpServletRequest request) throws IOException {

        User user = JWTUtil.getUserByToken(request);

        String url = QiNiuUploadUtils.uploadImage(null, file.getBytes());

        user.setImageUrl(url);
        userService.update(user);

        Map<String,String> map = new HashMap<>();
        map.put("url",url);

        return JSON.toJSONString(map);

    }

    @RequestMapping("/updatePassword")//修改密码
    public String updatePassword(User user){
        int i = userService.update(user);
        if (i==1){
            return "修改成功";
        }
        return "修改失败";
    }

    @RequestMapping(value = "/test")
    public String test(){

        return "测试测试";
    }
}

